package com.swd.order.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.swd.order.Enums.OrderEnum;
import com.swd.order.mapper.OrderMapper;
import com.swd.order.model.Foods;
import com.swd.order.model.Order;
import com.swd.order.model.OrderCommitModel;
import com.swd.order.model.OrderExample;
import com.swd.order.vo.OrderVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private FoodsService foodsService;
    @Autowired
    private OrderItemService orderItemService;



    public int orderSave(OrderCommitModel orderCommitModel, int userId) throws Exception {

        //验证
        orderValidator(orderCommitModel);


        Order order = new Order();
        OrderCommitModel.OrderBean.DetailBean detail = orderCommitModel.getOrder().getDetail();


        order.setMealTime(new Date(Long.parseLong(detail.getDate())));

        order.setFlavorId(detail.getFlavor());
        order.setPlaceId(detail.getPlace());
        order.setUserId(userId);
        order.setNum(detail.getNum());
        order.setStatus(OrderEnum.CREATE.getByteCode());
        order.setRemark(detail.getRemark());
        order.setMealType(detail.getMealType());


        Integer orderId = orderInsert(order);
        if (orderId == null) {
            log.error("订单保存失败,order:{}", order);
            throw new Exception("订单保存失败");
        }

        List<Foods> foods = orderCommitModel.getOrder().getDetail().getFoods().stream().map(item -> {
            Foods food = new Foods();
            food.setId(item.getId());
            food.setNum(item.getNum());
            return food;
        }).collect(Collectors.toList());

        log.info("开始保存订单{}", foods);

        boolean orderItemSaveSuccess = orderItemService.orderItemSave(foods, orderId,Boolean.FALSE);

        List<Integer> foodsIdList = foods.stream().map(Foods::getId).collect(Collectors.toList());

        boolean foodsCountIncreaseSuccess = foodsService.foodsCountIncrease(foodsIdList);

        if (!(orderItemSaveSuccess && foodsCountIncreaseSuccess)) {
            throw new Exception("订单保存失败");
        }

        return orderId;
    }

    private Integer orderInsert(Order order) {

        int insert = orderMapper.insertSelective(order);

        return insert == 0 ? null : order.getId();

    }

    private List<Foods> orderValidator(OrderCommitModel order) throws Exception {

        List<String> errMsg = new ArrayList<>();

        List<OrderCommitModel.OrderBean.DetailBean.FoodsBean> foodsList = order.getOrder().getDetail().getFoods();
        List<Integer> foodIdList = foodsList.stream().map(OrderCommitModel.OrderBean.DetailBean.FoodsBean::getId).collect(Collectors.toList());
        List<Foods> foods = foodsService.queryInIdList(foodIdList);

        if (foodsList.size() != foods.size()) {
            log.error("有菜品不存在{},{}", foodsList, foods);
            throw new Exception("菜品不存在");
        }

        boolean success = foods.stream().anyMatch(item -> item.getEnable() && item.getOftenMeal());

        if (!success) {
            throw new Exception("有菜品未上架或者无食材，订单保存失败。");
        }

        return foods;
    }

    public Order queryOrderById(int id) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andIdEqualTo(id);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        if (orders.size() > 0) {
            return orders.get(0);
        }
        return null;
    }

    public OrderVo queryById(int id) {
        List<OrderVo> orderVos = orderMapper.queryById(id);

        if (orderVos.size() > 0) {
            return orderVos.get(0);
        }

        return null;

    }

    public Page<OrderVo> queryAll(int pageNum, int limit) {
        Page<OrderVo> pageHelper = PageHelper.startPage(pageNum, limit);
        orderMapper.queryAll();

        return pageHelper;
    }

    public int update(Order order) {
        return orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     * 获取可加餐的订单
     * @return
     */
    public List<OrderVo> queryOrderVoAddMealEnable() {

        List<OrderVo> orderVoList = orderMapper.queryOrderVoByStatus(Arrays.asList(OrderEnum.CREATE.getByteCode(),
                OrderEnum.MEAL.getByteCode()));
        return orderVoList;
    }

    public boolean extraOrderSave(OrderCommitModel order) throws Exception {
        orderValidator(order);

        Integer extraMealId = order.getOrder().getExtraMealId();

        Order extraOrder = queryOrderById(order.getOrder().getExtraMealId());

        if (extraOrder==null){
            throw new Exception("订单不存在");
        }

        if (extraOrder.getStatus() == OrderEnum.FINISH.getByteCode()){
            throw new Exception("订单已完成");
        }

        List<Foods> foods = order.getOrder().getDetail().getFoods().stream().map(item -> {

            return Foods.builder().id(item.getId()).num(item.getNum()).build();

        }).collect(Collectors.toList());

        List<Integer> collect = foods.stream().map(Foods::getId).collect(Collectors.toList());

        boolean orderItemSaveSuccess = orderItemService.orderItemSave(foods, order.getOrder().getExtraMealId(), Boolean.TRUE);

        boolean foodsCountIncreaseSuccess = foodsService.foodsCountIncrease(collect);

        return foodsCountIncreaseSuccess && orderItemSaveSuccess;
    }
}
